package com.csbc.arithmetic.market;

import com.csbc.arithmetic.coupon.BasePromotion;
import com.csbc.arithmetic.coupon.CouponPromotion;
import com.csbc.arithmetic.fruit.Fruit;
import com.csbc.arithmetic.shopping.Shopping;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class SuperMarket implements Market {

    private Shopping[] shopping;

    private BasePromotion basePromotion;

    private SuperMarket() {

    }

    public SuperMarket(Shopping... shopping) {
        this.shopping = shopping;
    }

    public SuperMarket(BasePromotion basePromotion, Shopping... shopping) {
        this.shopping = shopping;
        this.basePromotion = basePromotion;
    }

    @Override
    public BigDecimal checkout() {
        BigDecimal total = new BigDecimal("0");
        HashMap<String, Integer> fruitWeight = new HashMap<>();
        if (shopping.length > 0) {
            for (Shopping value : shopping) {
                HashMap<Fruit, Integer> hashMap = value.getShoppingTrolley();
                for (Map.Entry<Fruit, Integer> entry : hashMap.entrySet()) {
                    if (entry.getKey().isPromotion()) {
                        total = total.add(entry.getKey().getPromotionPrice().multiply(BigDecimal.valueOf(entry.getValue())));
                    } else {
                        total = total.add(BigDecimal.valueOf(entry.getKey().getPrice()).multiply(BigDecimal.valueOf(entry.getValue())));
                    }
                    fruitWeight.compute(entry.getKey().getClass().getSimpleName(), (v,k)->k==null?entry.getValue():k+entry.getValue());
                }
            }
        }
        for (Map.Entry<String, Integer> stringIntegerEntry : fruitWeight.entrySet()) {
            System.out.println("顾客总共买了"+stringIntegerEntry.getKey()+":"+stringIntegerEntry.getValue()+"斤");
        }
        if (Optional.ofNullable(this.basePromotion).isPresent()) {
            System.out.println("原价是:" + total.setScale(2, RoundingMode.HALF_UP) + "元");
            total = basePromotion.doPromotion(total);
        }
        return total.setScale(2, RoundingMode.HALF_UP);
    }
}
